package com.huosu.config;


import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：liyingchun
 * @date ：Created in 2019/7/5 0005 11:47
 * @description：Web配置
 * @modified By：
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 配置全局跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }


    /**
     * 使用阿里 fastjson替代Jackson作为 JSON MessageConverter
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //添加fastJson的配置信息;
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                // 保留 Map 空的字段
                SerializerFeature.WriteMapNullValue,
                // 将 String 类型的 null 转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将 Number 类型的 null 转成 0
                SerializerFeature.WriteNullNumberAsZero,
                // 将 List 类型的 null 转成 []
                SerializerFeature.WriteNullListAsEmpty,
                // 将 Boolean 类型的 null 转成 false
                SerializerFeature.WriteNullBooleanAsFalse,
                //全局修改日期格式
                SerializerFeature.WriteDateUseDateFormat,
                //格式化输出
                SerializerFeature.PrettyFormat,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);
        //全局时间配置
        //如果时间类型值为null，则返回空串
        ValueFilter dateFilter = (Object var1, String var2, Object var3) -> {
            try {
                if (var3 == null && var1 != null && Date.class.isAssignableFrom(var1.getClass().getDeclaredField(var2).getType())) {
                    return "";
                }
            } catch (Exception e) {
            }
            return var3;
        };
        config.setSerializeFilters(dateFilter);
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        //处理中文乱码问题
        config.setCharset(Charset.forName("UTF-8"));

        //在convert中添加配置信息.
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(fastMediaTypes);

        converter.setFastJsonConfig(config);
        converters.add(0, converter);
    }

}
